// pages/Systems/AddFeedback/AddFeedback.js
//获取应用实例
const app = getApp()
import { queryUserSuggestionsTitle , updateUserSuggestions } from '../../../api/brand';
import { getGoodsOrder } from '../../../api/order';
import { REFRESH_TOKEN } from '../../../utils/types';
import { throttle } from '../../../utils/util';
import { checkFile } from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadFileUrl: app.globalData.global.uploadFileUrl,
    brandId: app.globalData.global.brandId,
    typeList: [],
    type: '',
    order: {}, // 资讯订单
    goodsName: '', // 搜索商品名称
    page: 0,
    isReachBottom: false,
    noMore: false,
    loading: false,
    loadingFailed: false,
    dataList: [],
    showOrder: false,
    autosize: { minHeight: 80 },
    fileList: [],
    question: '', // 问题
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._queryUserSuggestionsTitle();
    this._getOrders();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取投诉标题
  _queryUserSuggestionsTitle(){
    let _this = this;
    queryUserSuggestionsTitle({})
    .then(res => {
      if(res.success){
        _this.setData({
          typeList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择类型
  selType(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      type: item.id,
    })
  },
  // 查询订单数据
  _getOrders(){
    let _this = this;
    getGoodsOrder({goodsName: _this.data.goodsName,page: _this.data.page,})
    .then(async (res) => {
      if(res.success){
        var data = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.goodsInfo = JSON.parse(item.goodsInfo);
          item.receivingAddressInfo = JSON.parse(item.receivingAddressInfo);
          data.push(item);
        }
        var list = _this.data.dataList;
        if(_this.data.page == 0){
          list = data;
        }else{
          list.concat(data);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  selOrder(){
    this.setData({
      showOrder: true,
    })
  },
  onClose(){
    this.setData({
      showOrder: false,
    })
  },
  goodNameChange(e){
    this.setData({
      goodsName: e.detail,
    });
  },
  selOrderByGoodsName(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrders();
  },
  // 加载更多数据
  onLoadMore: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._getOrders()
    }
  },500),
  selOrders(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      order: item,
      showOrder: false,
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 选择图片
  afterRead(event) {
    let _this = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    console.log(file,'file')
    var token = wx.getStorageSync('access_token')
    wx.uploadFile({
      url: _this.data.uploadFileUrl, // 上传接口
      filePath: file.url,
      name: 'file',
      formData: { 'brandId': _this.data.brandId ,'access_token': token,},
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = _this.data;
        // fileList.push({ ...file, url: res.data });
        console.log(res,'res')
        var res = JSON.parse(res.data);
        if(res.success){
          var types = checkFile(res.data);
          if(types == 'video'){
            fileList.push({url: res.data,isVideo: true,deletable: true})
          }else if(types == 'image'){
            fileList.push({url: res.data,isImage: true,deletable: true})
          }
          console.log(fileList,'fileList')
          _this.setData({ fileList });
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      },
    });
  },
  // 删除图片
  deleteImg(e){
    console.log(e)
    let list = this.data.fileList
    list.splice(e.detail.index,1)
    this.setData({
      fileList: list,
    })
  },
  qusChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      question: event.detail,
    })
  },
  // 提交反馈
  submit(){
    let _this = this;
    console.log(_this.data.question,'question')
    if(_this.data.type == ''){
      wx.showToast({
        title: '请选择反馈类型',
        icon: 'none'
      })
      return;
    }
    if(_this.data.question == ''){
      wx.showToast({
        title: '请输入反馈问题',
        icon: 'none'
      })
      return;
    }
    var tag = _this.data.typeList.find(item => item.id == _this.data.type);
    var imgUrlArr = [];
    for (let index = 0; index < _this.data.fileList.length; index++) {
      const item = _this.data.fileList[index];
      imgUrlArr.push(item.url);
    }
    var userId = wx.getStorageSync('userId');
    var phone = wx.getStorageSync('phone');
    updateUserSuggestions({orderCode: _this.data.order.orderCode,tagId: _this.data.type,tagName: tag.tagName,question: _this.data.question,imgUrl: imgUrlArr.join(','),userId: userId,phone: phone})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '反馈成功',
          icon: 'success',
        })
        wx.navigateBack({
          delta: 1,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})